import 'package:file_picker/file_picker.dart';
import 'package:file_preview/file_preview.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:live_music/config/style/DQColor.dart';
import 'package:live_music/pages/home/index/index.dart';
import 'package:live_music/pages/home/message/index.dart';
import 'package:live_music/pages/home/mime/index.dart';
import 'package:live_music/pages/home/square/square.dart';
import 'package:live_music/pages/login/login.dart';
import 'package:live_music/pages/publish/index.dart';
import 'package:live_music/pages/publish/douyin_publish.dart';
import 'package:live_music/services/userService.dart';
import 'package:live_music/utils/common.dart';
import 'package:live_music/utils/log_utils.dart';
import 'package:live_music/utils/sp_utils.dart';
import 'package:live_music/utils/toast_utils.dart';
import 'package:live_music/utils/util.dart';
import 'package:proste_indexed_stack/proste_indexed_stack.dart';
import 'package:ripple_backdrop_animate_route/ripple_backdrop_animate_route.dart';

// 导航集合
const List<Map> _bottomBarList = [
  {
    'icon': 'home.png',
    'activeIcon': 'home_active.png',
    'label': '首页',
  },
  {
    'icon': 'music.png',
    'activeIcon': 'music_active.png',
    'label': '广场',
  },
  {
    'icon': 'create_media.png',
    'activeIcon': 'create_media.png',
    'label': '',
  },
  {
    'icon': 'tiny_video.png',
    'activeIcon': 'tiny_video_active.png',
    'label': '发现',
  },
  {
    'icon': 'profile.png',
    'activeIcon': 'profile_active.png',
    'label': '我的',
  }
];

// 应用根页面
class AppPage extends StatefulWidget {
  final int index;
  AppPage({Key key, this.index}) : super(key: key);
  @override
  _AppPageState createState() => _AppPageState();
}

class _AppPageState extends State<AppPage> {
  int _currentIndex = 0;
  final List<Widget> _pageList = [
    PageViewIndex(),
    PageViewSquare(),
    Container(),
    MessageIndexPage(),
    PageViewMime(),
  ];

  @override
  void initState() {
    _currentIndex = widget.index != null ? widget.index : 0;
    super.initState();
    // checkToken();
    initData();
  }

  initData() async {
    await FilePreview.initTBS();
    await SPUtil.init();
    LogUtils.init();
  }

  checkToken() async {
    // Future.delayed(Duration(milliseconds: 500), () {
    //   Get.to(FeedPublishPage());
    // });
    Map<String, dynamic> localuserLogin = await SPUtil.getObject('userLogin');
    if (localuserLogin == null) {
      Get.to(LoginPage());
    }
    await UserService.checkLoginToken();
  }

  void _onTabbarClick(int index) {
    if (index == 2) {
      return _onCreateMediaClick();
    }
    setState(() {
      _currentIndex = index;
    });
  }

  // 发布媒体
  void _onCreateMediaClick() {
    Navigator.of(context).push(TransparentRoute(
      builder: (BuildContext context) => RippleBackdropAnimatePage(
        child: Container(
          alignment: Alignment.bottomCenter,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                icon: Icon(
                  Icons.image,
                  size: 36,
                ),
                onPressed: () async {
                  Get.off(FeedPublishPage(publishType: PublishType.moment));
                },
              ),
              IconButton(
                icon: Icon(Icons.video_call, size: 36),
                onPressed: () async {
                  PublishFileMgs publishFileMgs = PublishFileMgs();
                  FilePickerResult result = await FilePicker.platform.pickFiles(
                    type: FileType.video,
                  );
                  publishFileMgs.size = changeSize(result.files.first.size);
                  publishFileMgs.name = result.files.first.name;
                  publishFileMgs.path = result.files.first.path;
                  if (result.files.first.size > 1024 * 1024 * 1024) {
                    ToastUtils.showToast('视频最大为1G');
                    return;
                  }
                  Get.off(FeedPublishPage(
                      publishFileMgs: publishFileMgs,
                      publishType: PublishType.video));
                },
              ),
              IconButton(
                icon: Icon(Icons.upload_file, size: 36),
                onPressed: () async {
                  PublishFileMgs publishFileMgs = PublishFileMgs();
                  FilePickerResult result = await FilePicker.platform.pickFiles(
                    type: FileType.custom,
                    allowedExtensions: ['pdf'],
                  );
                  publishFileMgs.size = changeSize(result.files.first.size);
                  publishFileMgs.name = result.files.first.name;
                  publishFileMgs.path = result.files.first.path;
                  if (result.files.first.size / 1024 / 1024 > 20) {
                    ToastUtils.showToast('附件大小不能超过20M');
                    return;
                  }
                  Get.off(FeedPublishPage(
                      publishFileMgs: publishFileMgs,
                      publishType: PublishType.file));
                },
              ),
              IconButton(
                icon: Icon(Icons.video_settings, size: 36),
                onPressed: () async {
                  Get.off(DouYinPulish());
                },
              ),
            ],
          ),
        ),
        childFade: true,
        duration: 300,
        blurRadius: 20.0,
        bottomButton: const Icon(Icons.close),
      ),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ProsteIndexedStack(
        index: _currentIndex,
        children: _pageList,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: _bottomNavigationBarItems(),
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        onTap: _onTabbarClick,
      ),
      floatingActionButton: _createMediaButton(),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  // 发布媒体按钮
  Widget _createMediaButton() {
    return Container(
      width: 44,
      height: 44,
      margin: EdgeInsets.only(top: 56),
      child: FloatingActionButton(
        backgroundColor: DQColor.nav,
        elevation: 0,
        child: Image.asset('assets/images/icons/create_media.png'),
        onPressed: _onCreateMediaClick,
      ),
    );
  }

  // 生成底部导航
  List<BottomNavigationBarItem> _bottomNavigationBarItems() {
    return _bottomBarList.map((item) {
      return BottomNavigationBarItem(
        icon: Image.asset(
          'assets/images/icons/' + item['icon'],
          width: 24,
          height: 24,
        ),
        activeIcon: Image.asset(
          'assets/images/icons/' + item['activeIcon'],
          width: 24,
          height: 24,
        ),
        label: item['label'],
        tooltip: '',
      );
    }).toList();
  }
}
